import pymongo
import os,re
import time

client = pymongo.MongoClient("localhost", 27017)
db = client.test
from scrapy import signals

# class testdown(scrapy.downloadermiddlewares.DownloaderMiddleware):
#     def process_request(request, spider):
#         return None

class testdown(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.
        
        rs=db.cache2.find_one({"url":request.url})
        if rs:
            return rs["res"]
        else:
            return None
        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        # return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        # db.cache2.insert_one({"url" : response.url, "res": response.body})
        db.cache2.insert_one({"url" : response.url, "html": response.body})
        # db.cache3.
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened ccccc: %s' % spider.name)

